package com.yfeng.goodjuhome.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.yfeng.common.utils.Util;
import com.yfeng.exception.ServiceException;
import com.yfeng.goodjuhome.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;




import com.yfeng.common.dao.IDao;
import com.yfeng.common.dao.Param;
import com.yfeng.common.utils.BeanUtil;

import com.yfeng.goodjuhome.service.IUserService;

@Service("userService")
public class UserServiceImpl implements IUserService {

	private final Log log = LogFactory.getLog(this.getClass());
	@Autowired
	public IDao baseDao;
	User user = null;
	
	/*
	 * 添加用户
	 * @see com.bw.callcenter.sys.service.IUserService#addUser(com.bw.callcenter.sys.model.User, com.bw.callcenter.sys.model.UserGroup, java.lang.String)
	 */

	public int addUser(User user)  throws ServiceException{

		
//		User user = (User)BeanUtil.getBean("user");
//		if (user.isExist(username))
//			return -1;
//
//		Param param = new Param();
//		param.put("username", user.getUsername());
//		param.put("passwd", passwd);
//		param.put("groupid", groupid);
//		param.put("regdate", DateUtil.getCurDateTime());
//		param.put("point", point);
//		param.put("type", type);
//		param.put("uid", userid);
//		int pk = baseDao.save("users", param);
//		if (pk > 0) {
//			return 1;
//		}
		return 0;

	}
	
	/*
	 * 修改用户
	 * @see com.bw.callcenter.sys.service.IUserService#modUser(com.bw.callcenter.sys.model.User, com.bw.callcenter.sys.model.UserGroup, java.lang.String)
	 */

	public int modUser(String uid,String passwd,String groupid,String point,String type)  throws ServiceException{
		if(type==null || "".equals(type)){
			type="2";
		}
		Param param = new Param();
		try
        {
		param.put("passwd", passwd, Param.VALUE);
		param.put("groupid", groupid, Param.VALUE);	
		param.put("point", point,Param.VALUE);
		param.put("type", type,Param.VALUE);
		param.put("id", uid, Param.CONDITION);
		int pk = baseDao.save("users", param);
		return pk;
        }
        catch (Exception e)
        {
            log.error(e.getMessage(),e);
            throw new ServiceException(e.getMessage(),e);
        }

	}


    public User getUser(String id) throws ServiceException {

        try {
            List result = baseDao.query("select * from users where id=:id",new Param("id",id));

            if(result.size()>0)
            {

                Map map = (Map) result.get(0);

                String mid = Util.getEmptyStr(map.get("id"));
                String username = Util.getEmptyStr(map.get("username"));
                String passwd = Util.getEmptyStr(map.get("passwd"));
                String usertype = Util.getEmptyStr(map.get("usertype"));
                String email = Util.getEmptyStr(map.get("email"));
                String homecode = Util.getEmptyStr(map.get("homoecode"));
                String enable = Util.getEmptyStr(map.get("enable"));

                String createtime = Util.getEmptyStr(map.get("createtime"));
                String regdate = Util.getEmptyStr(map.get("regdate"));

                User user = new User(mid,username,passwd,email,usertype,enable,homecode,createtime,regdate);
                            
                return user;
            }
            else
                return null;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new ServiceException(e.getMessage(),e);
        }
    }

    public User getUserByName(String username) throws ServiceException {
       try {
            List result = baseDao.query("select * from users where username=:username",new Param("username",username));

            if(result.size()>0)
            {

                Map map = (Map) result.get(0);

                String mid = Util.getEmptyStr(map.get("id"));
                String passwd = Util.getEmptyStr(map.get("passwd"));
                String usertype = Util.getEmptyStr(map.get("usertype"));
                String email = Util.getEmptyStr(map.get("email"));
                String homecode = Util.getEmptyStr(map.get("homoecode"));
                String enable = Util.getEmptyStr(map.get("enable"));

                String createtime = Util.getEmptyStr(map.get("createtime"));
                String regdate = Util.getEmptyStr(map.get("regdate"));

                User user = new User(mid,username,passwd,email,usertype,enable,homecode,createtime,regdate);

                return user;
            }
            else
                return null;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new ServiceException(e.getMessage(),e);
        }
    }

    public int toLogin(String username,String passwd,String usertype) throws ServiceException {

        try
        {
		int i=baseDao.getRowCount("from users where username='"+username+"' and passwd='"+passwd+"' and usertype='"+usertype+"'  and enable=0",new Param());
		if(i>0){
			return 0;
		}
        else
            return -1;
        }
        catch(Exception e)
        {
            log.error(e.getMessage(),e);
            throw new ServiceException(e.getMessage(),e);
        }
		

	}
	

	public boolean toLogin(String username, String passwd) throws ServiceException {
		User user = (User)BeanUtil.getBean("user");
        try
        {
		List ret =baseDao.query("select id from users where username='"+username+"' and passwd='"+passwd+"' and usertype>0 and enable=0",new Param());
		
		return ret.size()>0;
        }
        catch(Exception e)
        {
            log.error(e.getMessage(),e);
            throw new ServiceException(e.getMessage(),e);
        }
		
	}

   

    public User getUser() {
		return user;
	}


	/**
	 * 删除用户
	 */
	public int deleteUser(String[] ids,String method) throws ServiceException {

		try {
			if("lock".equals(method)){
				List paramList=new ArrayList();
				for (int i = 0; i < ids.length; i++) {
					
	
					Param p=new Param();
					p.put("value__enable", "1");
					p.put("cond__id", ids[i]);
					paramList.add(p);
	
					//				baseDao.delete("user_group", new Param("userid", ids[i]));
				}
				baseDao.batchSave("users",paramList);
				return 1;
			}else if("unlock".equals(method)){
				List paramList=new ArrayList();
				for (int i = 0; i < ids.length; i++) {
					
					Param p=new Param();
					p.put("value__enable", "0");
					p.put("cond__id", ids[i]);
					paramList.add(p);
	
					//				baseDao.delete("user_group", new Param("userid", ids[i]));
				}
				baseDao.batchSave("users",paramList);
				return 3;
			}


		}
        catch(Exception e)
        {
            
        }


		return 0;

	}
	
	public List getPermissionIdsByUser(String userid) throws Exception{
		List ret=baseDao.query("select pid from user_permission where uid="+userid);
		List idList=new ArrayList();
		for(int i=0;i<ret.size();i++){
			Map m=(Map)ret.get(i);
			idList.add(m.get("pid").toString());
		}
		return idList;
	}
	public int givenPermission(String[] ids,String userid,List permissionList) throws Exception{
		for(int i=0;i<permissionList.size();i++){
			Map m=(Map)permissionList.get(i);
			String pid=m.get("id").toString();
			baseDao.deleteBySql("delete from user_permission where uid="+userid+" and pid="+pid, new Param());
		}
		if(ids!=null){
			List paramsList=new ArrayList();
			for(int i=0;i<ids.length;i++){
				Param p=new Param();
				p.put("uid", userid);
				p.put("pid", ids[i]);
				paramsList.add(p);
			}
			int[] ret=baseDao.batchSave("user_permission", paramsList);
			if(ret[0]==-1){
				return -1;
			}else{
				return 1;
			}
		}else{
			return 1;
		}

	}
	
	public int updatePoint(String uid,String point){
		Param p = new Param();
		p.put("point", point,Param.VALUE);
		p.put("id", uid, Param.CONDITION);
		int ret = 0;
		try {
			
			ret = baseDao.save("users", p);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
	public int updateLastPoint(String uid,String point){
		Param p = new Param();
		p.put("tmp", point,Param.VALUE);
		p.put("id", uid, Param.CONDITION);
		int ret = 0;
		try {
			
			ret = baseDao.save("users", p);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
	
	public int updateTmp(String uid,String point){
		Param p = new Param();
		p.put("tmp2", point,Param.VALUE);
		p.put("id", uid, Param.CONDITION);
		int ret = 0;
		try {
			
			ret = baseDao.save("users", p);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}


    public boolean isExist(String uid) throws ServiceException {
       try
       {
        int ret = baseDao.getRowCount("from users where id=:id", new Param("id",uid));
        if (ret > 0)
            return true;
        else
            return false;
       }
       catch(Exception e)
       {
           log.error(e.getMessage(),e);
           throw new ServiceException(e.getMessage(),e);
       }

    }


	public int editProfile(String uid,String oldpasswd, String passwd) {
Param param = new Param();
		
		param.put("passwd", passwd, Param.VALUE);	
		param.put("passwd", oldpasswd, Param.CONDITION);
		param.put("id", uid, Param.CONDITION);
		int pk = 0;
		try {
			pk = baseDao.save("users", param);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return pk;
	}

}
